package cool.tianyou.blue.bird.common.model.entity;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.Session;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author Liutianyou
 * @date 2021/7/17 10:13 下午
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ClientSession {
    private Integer userId;
    private ConcurrentHashMap<Integer, HeartBeatSession> userSessions = new ConcurrentHashMap<>();

    public Integer getUserId() {
        return userId;
    }

    public ClientSession(Integer userId) {
        this.userId = userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    /**
     * 添加一个Session
     *
     * @param deviceId 设备id
     * @param session  session
     */
    public void addSession(Integer deviceId, Session session) {
        userSessions.put(deviceId, new HeartBeatSession(session));
    }

    public void removeSession(Integer deviceId) {
        userSessions.remove(deviceId);
    }


    /**
     * 更新Session上次心跳事件
     *
     * @param deviceName 设备唯一Id
     */
    public void updateBeatTime(String deviceName) {
        HeartBeatSession heartBeatSession = userSessions.get(deviceName);
        Optional.ofNullable(heartBeatSession).ifPresent(hb -> {
            hb.setLastBeatTime(System.currentTimeMillis());
        });
    }
}
